<?php
namespace App\Http\Controllers\Api;

use App\Common\Exceptions\AixinException;
use App\Common\Exceptions\AixinExceptionCode;
use App\Common\Service\PassportService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Log;


class PassportController extends Controller {

    /**
     * 验证type
     */
    public function validateType() {

//        return $type;

    }

    /**
     *  demo
     */
    public function index() {
        Redis::set("uidemo123","d123123");
        $res = Redis::get("uidemo123");

        return $res;

    }

    public function sendcode(Request $request, PassportService $passportService) {
        $mobile  = $request->mobile;
        $imgCode = $request->img_code;
        if(empty($mobile) || empty($imgCode)) {
            throw new AixinException(AixinExceptionCode::MISSING_PARAM);
        }

        $isSend =  $passportService->sendcode($mobile, $imgCode);
        if(!$isSend) {
            throw new AixinException(AixinExceptionCode::RESULT_NULL);
        }

        $data = [];

        return ApiResponse($data);

    }

    public function imgCode(Request $request, PassportService $passportService) {
        $mobile = $request->mobile;
        if(empty($mobile)) {
            throw new AixinException(AixinExceptionCode::MISSING_PARAM);
        }
        $imgRes = $passportService->getImgCode($mobile);
        $base64Img = base64_encode($imgRes);
        $data = [
            'imgcode_base64'=>$base64Img,
        ];


        return ApiResponse($data);

    }


    public function login(Request $request, PassportService $passportService) {

        $mobile = $request->mobile;
        $phoneCode = $request->vcode;
        $isCheckPhoneCode = $passportService->isCheckPhoneCode($mobile, $phoneCode);
        if(!$isCheckPhoneCode) {
            throw new AixinException(AixinExceptionCode::VCODE_INVALID);
        }

        $uid = $passportService->getUniqueUid($mobile);
        if(empty($uid)) {
            throw new AixinException(AixinExceptionCode::RESULT_NULL);
        }

        $token = $passportService->getToken($uid);
        if(empty($token) ) {
            throw new AixinException(AixinExceptionCode::TOKEN_NULL);
        }
        $data = [
            'uid'  =>   $uid,
            'token'=>   $token,
        ];

        return ApiResponse($data);


    }


}
